package utils;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Duration {

	private final GregorianCalendar begin;
	private final GregorianCalendar end;

	public GregorianCalendar getBegin() {
		return begin;
	}

	public GregorianCalendar getEnd() {
		return end;
	}

	/**
	 * Convert a xml datetime to a gregorian calendar.
	 * 
	 * @param begin
	 *            the xml datetime.
	 * @return beginCal the gregorian calendar.
	 */
	public static GregorianCalendar getCalendar(String begin) {
		GregorianCalendar beginCal = new GregorianCalendar();
		String[] beginDateHour = begin.split("T");
		String[] beginDate = beginDateHour[0].split("-");
		String[] beginMs = beginDateHour[1].split("\\.");
		String[] beginHour = beginMs[0].split(":");
		if (beginMs.length != 2) {// No ms in xml
			beginDateHour = begin.split("T");
			beginDate = beginDateHour[0].split("-");
			beginHour = beginDateHour[1].split(":");
			beginCal.set(Integer.parseInt(beginDate[0]),
					Integer.parseInt(beginDate[1]),
					Integer.parseInt(beginDate[2]),
					Integer.parseInt(beginHour[0]),
					Integer.parseInt(beginHour[1]),
					Integer.parseInt(beginHour[2]));
		} else {
			beginCal.set(Integer.parseInt(beginDate[0]),
					Integer.parseInt(beginDate[1]),
					Integer.parseInt(beginDate[2]),
					Integer.parseInt(beginHour[0]),
					Integer.parseInt(beginHour[1]),
					Integer.parseInt(beginHour[2]));
			beginCal.set(Calendar.MILLISECOND, Integer.parseInt(beginMs[1]));
		}
		return beginCal;
	}

	public Duration(String begin, String end) {
		this.begin = getCalendar(begin);
		this.end = getCalendar(end);
	}

	/**
	 * get duration in Millisecond
	 * 
	 * @return
	 */
	public long getTheDuration() {
		return end.getTimeInMillis() - begin.getTimeInMillis();
	}

}
